package cloud.xlh.digital_power_order.config;

import cloud.xlh.digital_power_order.util.StackTraceUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : xlh_osms
 * @ Author: XuLeHuang
 * @ Date: 2023/8/14 20:06
 * @ Description:
 */
@Slf4j
@Configuration
public class ThreadPoolConfig {

    @Bean("IOThreadPoolExecutor")
    public ThreadPoolExecutor IOThreadPoolExecutor() {
        return new ThreadPoolExecutor(12 , 24,1000, TimeUnit.MINUTES
        ,new ArrayBlockingQueue<>(100), r -> {
            Thread thread = new Thread(r);
            String name = thread.getName();
            String suffix = name.substring(name.lastIndexOf("-"));
            String newName = "IOThread".concat(suffix);
            thread.setName(newName);
            thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread t, Throwable e) {
                    log.error("Exception is in {} {}" , t.getName() , e.getMessage());
                    log.error("pushed init method，log print location is -> {}" , StackTraceUtil.getCurrentLocation(Thread.currentThread()));
                }
            });
            return thread;
        } , new ThreadPoolExecutor.CallerRunsPolicy());    }
}
